from win32com.client import DispatchEx, gencache
import os
import traceback


def doc2pdf(doc_file):
    word = DispatchEx('Word.Application')  # WPS改为Kwps.Application
    try:
        output_file = doc_file.split(".")
        doc = word.Documents.Open(doc_file)
        doc.SaveAs(output_file[0] + ".pdf", FileFormat=17)  # Word另存为PDF为17
        doc.Close()
        text = os.path.basename(doc_file) + "转换成功！！！\n"
        print(doc_file + "转换结束")
    except Exception as e:
        print("-" * 70)
        print(doc_file + "该文件出现异常")
        print(e)
        text = os.path.basename(doc_file)
        print("-" * 70)
        content = "-" * 70 + "\n" + os.path.basename(doc_file) + " 该文件转换失败" + "\n"
        content = content + str(e) + "\n" + "*" * 70 + "\n"
        text = text + content
        traceback.print_exc()
    finally:
        word.Quit()
    return text


def excel2pdf(excel_file):
    excel = DispatchEx('Excel.Application')  #
    try:
        output_file = excel_file.split(".")
        # 对表格进行操作
        books = excel.Workbooks.Open(excel_file, False)
        books.ExportAsFixedFormat(0, output_file[0] + ".pdf")
        books.Close(False)
        text = os.path.basename(excel_file) + "转换成功！！！\n"
        print(excel_file + "转换结束")
    except Exception as e:
        print("-" * 70)
        print(excel_file + "该文件出现异常")
        print(e)
        text = os.path.basename(excel_file)
        print("-" * 70)
        content = "-" * 70 + "\n" + os.path.basename(excel_file) + " 该文件转换失败" + "\n"
        content = content + str(e) + "\n" + "*" * 70 + "\n"
        text = text + content
        traceback.print_exc()
    finally:
        excel.Quit()
    return text


def ppt2pdf(ppt_file):
    gencache.EnsureModule('{00020905-0000-0000-C000-000000000046}', 0, 8, 4)
    ppt = DispatchEx('PowerPoint.Application')  #
    try:
        output_file = ppt_file.split(".")
        ppt_open = ppt.Presentations.Open(ppt_file, False, False, False)
        ppt_open.ExportAsFixedFormat(output_file[0] + ".pdf", 2, PrintRange=None)
        ppt_open.Close()
        text = os.path.basename(ppt_file) + "转换成功！！！\n"
        print(ppt_file + "转换结束")
    except Exception as e:
        print("-" * 70)
        print(ppt_file + "该文件出现异常")
        print(e)
        text = os.path.basename(ppt_file)
        print("-" * 70)
        content = "-" * 70 + "\n" + os.path.basename(ppt_file) + " 该文件转换失败" + "\n"
        content = content + str(e) + "\n" + "*" * 70 + "\n"
        text = text + content
        traceback.print_exc()
    finally:
        ppt.Quit()
    return text





